package com.bulk.list;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 对象数组 List<StudentDemo>，根据对象中的某个属性去重
 *
 * @author 散装java
 * @date 2022-09-19
 */
public class ListDuplicate {

    public static void main(String[] args) {
        List<StudentDemo> stuList = buildStudentList();
        // 1. Java8 distinct hashCode() equals()
        List<StudentDemo> collect1 = stuList.stream().distinct().collect(Collectors.toList());

        // 2. HashSet LinkedHashSet
        HashSet<StudentDemo> hashSet = new HashSet<>(stuList);
        ArrayList<StudentDemo> collect2 = new ArrayList<>(hashSet);

        // 3. Java8 collectingAndThen -> treeSet -> list
        List<StudentDemo> collect3 = stuList.stream()
                .collect(Collectors
                        .collectingAndThen(Collectors
                                .toCollection(() -> new TreeSet<>(Comparator.comparing(StudentDemo::getName))), ArrayList::new));

        // 4. TreeSet
        TreeSet<StudentDemo> treeSet = new TreeSet<>(Comparator.comparing(stu -> (stu.getName() + stu.getId())));
        treeSet.addAll(stuList);
        List<StudentDemo> collect4 = new ArrayList<>(treeSet);

        System.out.println(collect1);
        System.out.println(collect2);
        System.out.println(collect3);
        System.out.println(collect4);

    }

    private static List<StudentDemo> buildStudentList() {
        ArrayList<StudentDemo> list = new ArrayList<>();
        list.add(new StudentDemo(1, "散装java", 18));
        list.add(new StudentDemo(2, "散装java", 18));
        list.add(new StudentDemo(2, "散装java", 20));
        return list;
    }
}
